import React, { useState } from 'react';
import { Modal, Form, Button, Input, Select, InputNumber, Upload } from 'antd';
import { ProFormUploadButton } from '@ant-design/pro-form';
import { upload } from '@/services/ant-design-pro/apis';
import { UploadOutlined } from '@ant-design/icons';
import { message } from 'antd';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

message.config({
  maxCount: 1, // 控制同时显示的消息数量
});

const CreateProduct = (props) => {
  const formLayout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 15,
    },
  };

  const [formVals, setFormVals] = useState({});

  const classifys = props.classifys;

  const { onSubmit: handCreate, onCancel: handleModalVisible, createModalVisible } = props;

  // 提交表单
  const handleSubmit = async () => {
    try {
      const fieldVlas = await form.validateFields();
      fieldVlas.productPicture = fileName;
      handCreate({ ...fieldVlas });
      setFileList([]);
      setUploaded(false);
      onReset();
    } catch (err) {
      console.log(err);
    }
  };

  const onReset = () => {
    form.resetFields();
  };

  function normFile(e) {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }

  const [uploaded, setUploaded] = useState(false);
  const [fileName, setFileName] = useState('');
  const [fileList, setFileList] = useState([]);

  // 文件上传
  const handleCustomRequest = ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('uploadfile', file);

    // 执行自定义上传请求
    fetch('/api/product/image', {
      method: 'POST',
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        // 处理响应
        console.log(data);
        onSuccess(data, file);
        setFileName(data.data.split('\\')[5]);
        // const fileName = data.data.split("\\")[5];
        // const fileName = data.data.split("\\")
      })
      .catch((error) => {
        // 处理错误
        onError(error, file);
      });
  };

  // 上传之前处理图片
  function beforeUpload(file) {
    const isImage = file.type.startsWith('image/');

    if (!isImage) {
      message.error('只能上传图片文件！', 2);
      return false;
    }
    if (uploaded) {
      message.error('只能上传一张图片', 2);
      return false;
    }

    setUploaded(true);

    const newFileList = [...fileList, file];
    setFileList(newFileList);

    return isImage;
  }

  const [form] = Form.useForm();

  return (
    <Modal
      title="新建产品"
      width={540}
      visible={createModalVisible}
      destroyOnClose
      onCancel={() => {
        onReset();
        handleModalVisible(false);
      }}
      footer={[
        <Button key="reset" onClick={onReset}>
          重置
        </Button>,
        <Button
          type="primary"
          key="submit"
          onClick={() => {
            handleSubmit();
          }}
        >
          提交
        </Button>,
      ]}
    >
      <Form
        {...formLayout}
        initialValues={{
          productStatus: 99,
        }}
        form={form}
      >
        <FormItem
          label="产品名称"
          name="productName"
          rules={[
            {
              required: true,
              message: '产品名称是必须项',
            },
          ]}
        >
          <Input placeholder="请输入产品名称"></Input>
        </FormItem>
        <FormItem
          label="产品编码"
          name="productNum"
          rules={[
            {
              required: true,
              message: '产品编码是必须项',
            },
          ]}
        >
          <Input placeholder="请输入产品编码" rows={4} />
        </FormItem>

        <FormItem
          label="库存数量"
          name="inventory"
          rules={[
            {
              required: true,
              message: '库存数量是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入库存数量" style={{ width: '100%' }} />
        </FormItem>
        <FormItem
          label="成本价格(元)"
          name="primeCost"
          rules={[
            {
              required: true,
              message: '成本价格是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入成本价格" style={{ width: '100%' }} />
        </FormItem>

        <FormItem
          label="售卖价格(元)"
          name="sellingPrice"
          rules={[
            {
              required: true,
              message: '售卖价格是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入售卖价格" style={{ width: '100%' }} />
        </FormItem>

        <FormItem label="类型" name="classifyId">
          <Select placeholder="请选择类型">
            {classifys?.map((item) => {
              return <Option value={item.id}>{item.typeName}</Option>;
            })}
          </Select>
        </FormItem>

        <FormItem label="状态" name="status">
          <Select>
            <Option value={'PUTAWAY'}>上架</Option>
            <Option value={'DELIST'}>下架</Option>
          </Select>
        </FormItem>

        <Form.Item
          label="产品图片"
          name="file"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          rules={[
            {
              required: true,
              message: '请上传产品图片',
            },
          ]}
        >
          <Upload
            name="uploadfile"
            listType="picture-card"
            customRequest={handleCustomRequest}
            action="/api/product/image" // 上传图片的服务端接口
            beforeUpload={beforeUpload}
            onRemove={onRemove}
          >
            {fileList.length > 0 ? null : <Button icon={<UploadOutlined />}>点击上传</Button>}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateProduct;
